package com.hugoo.imp.slt;

import com.hugoo.core.Conf;
import com.hugoo.core.db.HSF;
import com.hugoo.core.db.mo.Record;
import com.hugoo.core.db.mo.RecordSet;
import com.hugoo.core.slt.AcFwd;
import com.hugoo.core.slt.Action;
import com.hugoo.core.util.TL;
import com.hugoo.imp.buzz.FileUpload;
import com.hugoo.imp.buzz.ImpDataBuzz;
import com.hugoo.imp.buzz.ImpInfoBuzz;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Lovelock.Chan
 */
public class ImpAction extends Action {

    /**
     * 加载通用上传结果集表 xxx.imp?m=load
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public AcFwd load(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (super.checkPara(request, response)) {
            String lct = Conf.getImpProp(_sid, "imp.location");
            request.setAttribute("_location", lct);
            request.setAttribute("_xid", _sid);
            return new AcFwd("/WEB-INF/tpl/imp/list.jsp");
        }
        return null;
    }

    /**
     * 加载通用上传页面
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public AcFwd open(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (super.checkPara(request, response)) {
            String tpl = Conf.getImpProp(_sid, Conf.IMP._imp_cust_tpl);
            if (TL.isEmpty(tpl)) {
                HttpSession session = request.getSession();
                String rx = (String) session.getAttribute("SEP." + _sid);//如果会话中存在键SEP.SID值，则采用自定义导入模式
                ImpInfoBuzz iib = null;
                if (TL.isEmpty(rx)) {
                    iib = new ImpInfoBuzz(_sid);
                } else {//采用自定义导出入口模式
                    iib = new ImpInfoBuzz(_sid, rx);
                }
                Map<String, Object> m = super.parsePara(request);
                Set<String> key = m.keySet();
                StringBuilder sb = new StringBuilder();
                for (String x : key) {
                    sb.append("<input type='hidden' name='").append(x).append("' value='").append(m.get(x)).append("' />");
                }
                request.setAttribute("iib", iib.info(sb.toString()));
                return new AcFwd("/WEB-INF/tpl/imp/upload.jsp?mx=upload");
            } else {
                request.setAttribute("MM_PARA", super.parsePara(request));
                return new AcFwd(tpl);
            }
        }
        return null;
    }

    /**
     * 上传数据
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public AcFwd upload(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (super.checkPara(request, response)) {
            String scod = TL.socd();
            new FileUpload().upload(_sid, scod, request);
            String url = Conf.getImpProp(_sid, Conf.IMP._imp_cpl_url);
            if (TL.isEmpty(url)) {
                return new AcFwd(_sid + ".imp?m=upinfo&scod=" + scod, true);
            } else {
                try {
                    boolean stp = true;
                    int x = 0;
                    while (stp) {//若存在跳转URL，需要查看是否导入完成。
                        Thread.sleep(10000);
                        RecordSet<Record> rs = HSF.query(null, "SELECT ISPASS FROM T_SYS_IMP_FILEMETA where sid='" + _sid + "' and scod='" + scod + "' and substr(ISPASS,3,1)<>'W'");
                        if (rs.next()) {
                            if (rs.getString("ISPASS").substring(2, 3).equals("Y")) {
                                stp = false;//若上传成功，则成功跳转
                            } else {
                                return new AcFwd(_sid + ".imp?m=upinfo&scod=" + scod, true);
                            }
                        } else {
                            x++;
                            if (x > 30) {//5分钟等待-异常
                                stp = false;
                                log.warn("出现死循环，无法检测当前导入状态，请联系管理员！");
                            }
                        }
                    }
                } catch (Exception e) {
                    log.info("线程受到干扰！", e);
                }
                String scx = (String) request.getAttribute("hiduri");
                if (TL.isEmpty(scx)) {
                    scx = "&";
                }
                return new AcFwd(url.indexOf("?") > 0 ? url + "&scod=" + scod + "&" + scx : url + "?scod=" + scod + "&" + scx, true);
            }
        }
        return null;
    }
    
    public AcFwd upinfo(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (super.checkPara(request, response)) {
            String scod = request.getParameter("scod");
            RecordSet<Record> rs = HSF.query(null, "select *  from v_SYS_IMP_FILEMETA where SCOD='" + scod + "'");
            if (rs.next()) {
                request.setAttribute("vli", rs.getClobStr("VERIFY_INFO"));
                request.setAttribute("rs", rs.getRecord());
                request.setAttribute("scod", scod);
                request.setAttribute("_sid", _sid);
            }
            request.setAttribute("title", Conf.getImpProp(_sid, Conf.IMP._imp_title));
            return new AcFwd("/WEB-INF/tpl/imp/upload.jsp?mx=vli");
        }
        return null;
    }

    /**
     * 删除上传数据
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public AcFwd delete(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (super.checkPara(request, response)) {
            String scod = request.getParameter("scod");
            System.out.println(scod);
            if (TL.isEmpty(scod)) {
                super.writeDataToClient(response, "EPS3:无效的导入批次！");
                return null;
            }
            String stx = ImpDataBuzz.ref().getMetaStatus(scod);
            if ("-".equals(stx)) {
                super.writeDataToClient(response, "EPS3:无效的导入批次！");
            } else if (stx.matches("^Y[Y|W]{1}[Y|-]{1}[Y|-]{1}$")) {//H:历史记录，F：流程记录，D：草稿记录
                super.writeDataToClient(response, "EPS4:本导入批次【" + scod + "】已锁定，无法删除！");
            } else {
                boolean rs = ImpDataBuzz.ref().deleteImpData(scod);
                scod = scod.toUpperCase();
                if (rs) {
                    super.writeDataToClient(response, "EPS5:导入批次【" + scod + "】删除成功！");
                } else {
                    super.writeDataToClient(response, "EPS6:导入批次【" + scod + "】删除失败！");
                }
            }
        }
        return null;
    }

    /**
     * 查看上传数据 xxx.imp?m=view&scod=rvsixd
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public AcFwd view(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (super.checkPara(request, response)) {
            request.setAttribute("_defaultMonth", TL.format(new Date(), "yyyy-MM"));
            request.setAttribute("_location", "数据导入-查看导入数据");
            request.setAttribute("_sid", _sid);
            Map<String, String> m = new HashMap();
            TL.parsePara(request.getParameter("_para_in_"), m, log);
            request.setAttribute("scod", m.get("scod"));//本处暂时不处理scod为空的情况
            return new AcFwd("/WEB-INF/tpl/imp/view.jsp");
        }
        return null;
    }

    /**
     * 下载
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public AcFwd download(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (super.checkPara(request, response)) {
            String tpe = request.getParameter("type");
            if ("file".equals(tpe)) {
                String scod = request.getParameter("scod");
                RecordSet<Record> rc = HSF.query(null, "select filepath,fileName from T_SYS_IMP_FILEMETA where SCOD='" + scod + "' and sid='" + _sid + "'");
                if (rc.next()) {
                    String fp = rc.getString("filepath");
                    String fileName = rc.getString("fileName");
                    File tmp = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
                    TL.copyFile(new File(fp), tmp);
                    super.writeDataToClient(request, response, tmp, fileName);
                }
            } else {
                HttpSession session = request.getSession();
                String rx = (String) session.getAttribute("SEP." + _sid);//如果会话中存在键SEP.SID值，则采用自定义导入模式

                ImpInfoBuzz iib = null;
                if (TL.isEmpty(rx)) {
                    iib = new ImpInfoBuzz(_sid);
                } else {
                    iib = new ImpInfoBuzz(_sid, rx);
                }
                File tmp = null;
                if ("templete".equals(tpe)) {
                    tmp = iib.getTemplete();
                } else if ("rule".equals(tpe)) {
                    tmp = iib.getRules();
                }
                if (tmp != null) {
                    super.writeDataToClient(request, response, tmp, iib.getFileName(tpe));
                }
            }
        }
        return null;
    }
}
